import { XmDateTimePicker, XmDialogModal, XmToast } from "@/components/public";
import { XmImage } from "@/components/tool";
import { View } from "@tarojs/components";
import refundImg from "@/static/images/refund-bg.png";
// import { XmPedometer } from "@/components/ui";
// import { useEffect, useState } from "react";
import { payRefund } from "@/path/api/common";
import { TypeCommon, TypeOrderList, TypePayRefund } from "@/path/api/common/type";
import dayjs from "dayjs";

export function onRefund(item: { no: string, num: number }) {
  // const RefundNum = function (params: { onchange: (e: number) => void }) {
  //   const [num, setNum] = useState(1)
  //   function onSetNum(t: "add" | "del") {
  //     setNum(t === "add" ? num + 1 : num - 1)
  //   }
  //   useEffect(() => {
  //     params.onchange(num)
  //   }, [num])
  //   return <XmPedometer value={num} min={1} max={item.num} onChange={onSetNum}></XmPedometer>
  // }
  const params: TypePayRefund.parameter = {
    order: item.no,
    // num: 1
  }
  return XmDialogModal({
    content: <View className="refund-box">
      <XmImage src={refundImg} size="308*176" static></XmImage>
      <View className="s-lg-1-1 c-black f-weight-bold">确定要选择退票吗？</View>
      {/* <View className="flex flex-s s-lg c-black f-weight-bold refund-content bg-white">
        <Text>退票数量</Text>
        <RefundNum onchange={e => params.num = e}></RefundNum>
      </View> */}
    </View>,
    cancelText: "确定取消",
    confirmText: "保留门票",
  }).then((res) => {
    if (res === false) {
      return payRefund(params)
    } else {
      return Promise.reject()
    }
  }).then(() => {
    return XmToast.open("退票成功")
  }).then(() => {
    // return params.num
  })
}


export function chooseTimeDay(now: Date, commonInit: TypeCommon.returnedVal) {
  const _now = dayjs()
  let time: Date
  return XmDateTimePicker({
    title: "请选择购票日期",
    min: _now.toDate(),
    max: _now.add(1, "year").toDate(),
    type: "date",
    template: "YYYY-MM-DD",
    value: now,
    showWeek: true,
    onChange: e => time = e,
    filter(type, values) {
      if ((type === "day" || type === "month") && commonInit.prohibit_buy_date.length > 0) {
        const _mouth = type === "day" ? dayjs(time).format("YYYY-MM") : dayjs(time).format("YYYY")
        return values.filter(v => {
          const _times = commonInit.prohibit_buy_date.find(val => {
            return !dayjs(_mouth + v).isBetween(dayjs(val.start_date), dayjs(val.end_date), null, '[]')
          })
          return !!_times
        })
      }
      return values
    },
  })
}

function getGuoqi(order: TypeOrderList.Item) {
  // 获取今天的日期，并将时间设置为23:59:59  
  const todayEnd = dayjs().startOf("day");
  const _useTime = dayjs(Number(order.time) * 1000).endOf("day")
  if (_useTime.isBefore(todayEnd)) {
    return {
      text: "已过期",
      canUse: false
    }
  }
  return null
}

/**核销状态:0=未核销,1=已部分核销,2=已全部核销 */
// status: 0 | 1 | 2  // 
/**支付状态:0=待付款,1=已付款,2=部分退款,3全部退款 */
// pay_status: 1 | 0 | 2 | 3,     // 支付状态:0=待付款,1=已付款,2=部分退款,3全部退款
/**获取按钮文字 */
export function getButtonTxt(order: TypeOrderList.Item) {
  if (Number(order.status) === 0 && (Number(order.pay_status) === 1 || Number(order.pay_status) === 2)) {
    return getGuoqi(order) || {
      text: "待使用",
      canUse: true
    }
  }
  if (Number(order.status) === 1 && (Number(order.pay_status) === 1 || Number(order.pay_status) === 2)) {
    return getGuoqi(order) || {
      text: "已部分核销",
      canUse: true
    }
  }
  if (Number(order.status) === 2 && (Number(order.pay_status) === 1 || Number(order.pay_status) === 2)) {
    return {
      text: "已核销",
      canUse: false
    }
  }
  if (Number(order.pay_status) === 3) {
    return {
      text: "已退款",
      canUse: false
    }
  }
  if (Number(order.pay_status) === 0) {
    return getGuoqi(order) || {
      text: "待付款",
      canUse: false
    }
  }
}


export enum EnumPostion {
  "财神殿" = 1,
  "文昌殿" = 2,
  "三清殿" = 3,
}

type AsyncFunction = () => Promise<any>;

interface Polling {
  startPolling: () => void;
  stopPolling: () => void;
}
/**轮询 */
export function createPolling(asyncFunction: AsyncFunction, interval: number): Polling {
  let timeoutId: NodeJS.Timeout | null = null;

  async function poll(): Promise<void> {
    try {
      await asyncFunction();
    } catch (error) {
      console.error('Polling error:', error);
    }
    // 设置下一次轮询  
    timeoutId = setTimeout(poll, interval);
  }

  function startPolling(): void {
    // 如果已经有一个轮询在进行，则先停止它  
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
    }
    // 立即执行第一次轮询  
    poll();
  }

  function stopPolling(): void {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  }

  return {
    startPolling,
    stopPolling
  };
} 